import CommonConfig from '../global/CommonConfig';
import Handler = Laya.Handler;

/**
 * 资源加载管理
 * 每次有新资源或配置发布的时候，执行node buildResourceConfig.js更新配置即可
 */
export default class ResourceManager {
    private static resourcePath = "config/resource.json";


    /**
     * 加载本地资源
     * @param complete complete handler
     */
    public static loadLocalResource(complete: Handler, progress: Handler = null): void {
        Laya.loader.load([{ url: this.resourcePath, type: Laya.Loader.JSON }], Laya.Handler.create(this, () => {
            let resourceConfig = Laya.loader.getRes(this.resourcePath);
            let localResources = ResourceManager.buildResourceUrls(resourceConfig['local']);
            Laya.loader.load(localResources, complete, progress);
        }));
    }

    /**
     * 加载cdn资源
     * @param cdnHost cdn域名
     * @param complete complete handler
     * @param progress progress handler
     */
    public static loadCdnResource(cdnHost: string, version: string, complete: Handler, progress: Handler): void {
        let resourceConfig = Laya.loader.getRes(this.resourcePath);
        let cdnResources = ResourceManager.buildResourceUrls(resourceConfig['cdn']);
        cdnResources = cdnResources.map((resourceItem) => {
            if (typeof resourceItem === 'string') {
                return `${resourceItem}?v=${version}`;
            }
            resourceItem.url = `${resourceItem.url}?v=${version}`;
            return resourceItem;
        });

        Laya.URL.basePath = cdnHost;
        Laya.loader.load(cdnResources, complete, progress);
    }


    /**
     * 根据资源配置生成需要加载的url
     * @param resourceConfig 资源配置
     */
    private static buildResourceUrls(resourceConfig: any) {
        let resources = [];
        for (let obj of resourceConfig) {
            let type;
            if (obj['type'] == "json") {
                type = Laya.Loader.JSON;
            } else if (obj['type'] == "atlas") {
                type = Laya.Loader.ATLAS;
            } else if (obj['type'] == "image") {
                type = Laya.Loader.IMAGE;
            }
            if (type) {
                for (let url of obj['urls']) {
                    resources.push({ url: url, type: type })
                }
            } else {
                for (let url of obj['urls']) {
                    resources.push(url)
                }
            }
        }
        return resources;
    }
}